package com.example.demo.controller;

import com.example.demo.pojo.Anime;
import com.example.demo.repository.AnimeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpSession;
import java.util.Collections;

@Controller
public class AnimePageController {
@Autowired
private AnimeRepository animeRepository;

@GetMapping("/anime-list")
public String getAnimeList(@RequestParam(defaultValue = "0") int page, HttpSession session, Model model) {
    // 检查 Session 数据
    if (session.getAttribute("currentUser") == null) {
        return "redirect:/login"; // 重定向到登录页面
    }

    // 分页逻辑
    int pageSize = 8;
    Pageable pageable = PageRequest.of(page, pageSize);

    try {
        Page<Anime> animePage = animeRepository.findAll(pageable);

        // 检查页码是否超出范围
        if (page < 0) {
            return "redirect:/anime-list?page=0";
        }
        if (animePage.getTotalPages() > 0 && page >= animePage.getTotalPages()) {
            return "redirect:/anime-list?page=" + (animePage.getTotalPages() - 1);
        }

        // 将数据传递到前端
        model.addAttribute("animeList", animePage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", animePage.getTotalPages());
    } catch (Exception e) {
        // 记录日志并返回错误页面
        model.addAttribute("errorMessage", "An error occurred while fetching anime list. Please try again later.");
        model.addAttribute("animeList", Collections.emptyList());
        model.addAttribute("currentPage", 0);
        model.addAttribute("totalPages", 0);
    }

    return "anime-list"; // 返回视图名称
}
}